package com.ivan.stu.notetool.utils;

import android.content.Context;
import android.graphics.Color;
import android.support.v4.content.ContextCompat;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.CharacterStyle;
import android.text.style.ForegroundColorSpan;
import android.util.Log;

import com.blankj.utilcode.util.LogUtils;
import com.ivan.stu.notetool.R;


import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.nodes.TextNode;
import org.jsoup.select.Elements;
import org.jsoup.select.NodeTraversor;
import org.jsoup.select.NodeVisitor;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by IVAN on 2019/2/21.
 */

public class StringUtil {


    /**
     * @param targetStr 要处理的字符串
     * @description 切割字符串，将文本和img标签碎片化，如"ab<img>cd"转换为"ab"、"<img>"、"cd"
     */
    public static List<String> htmlAnalysis(String targetStr) {
        List<String> splitTextList = new ArrayList<String>();
        try {
            Document doc = Jsoup.parse(targetStr);
            Elements elements = doc.getAllElements();
            LogUtils.e(elements.size()+"");

            for(int i=0;i<elements.size();i++){
                if(elements.get(i).nodeName().equals("p")){
                    String text=convertNodeToText(elements.get(i));
                    if(!TextUtils.isEmpty(text)) {
                        LogUtils.e(text+"");
                        splitTextList.add(text);
                    }
                    if(elements.get(i).hasText()){

                    }
                }
                if(elements.get(i).nodeName().equals("img")){
                    LogUtils.e(elements.get(i).toString());
                    splitTextList.add(elements.get(i).toString());
                }

            }
            //打印 <a>标签里面的title
        }catch(Exception e) {
            Log.e("mytag", e.toString());
        }
        return splitTextList;
    }

    public static String convertNodeToText(Element element)
    {
        final StringBuilder buffer = new StringBuilder();

        new NodeTraversor(new NodeVisitor() {
            boolean isNewline = false;

            @Override
            public void head(Node node, int depth) {
                if (node instanceof TextNode) {
                    TextNode textNode = (TextNode) node;
                    String text = textNode.text().replace('\u00A0', ' ').trim();
                    if(!text.isEmpty())
                    {
                        buffer.append(text);
                        isNewline = false;
                    }
                } else if (node instanceof Element) {
                    Element element = (Element) node;
                    if(element.tagName().equals("br"))
                    {
                        buffer.append("\n");
                        isNewline = true;
                    }
                }
            }

            @Override
            public void tail(Node node, int depth) {
            }
        }).traverse(element);
        return buffer.toString();
    }

    /**
     * 获取img标签中的src值
     *
     * @param content
     * @return
     */
    public static String getImgSrc(String content) {
        String str_src = null;
        //目前img标签标示有3种表达式
        //<img alt="" src="1.jpg"/>   <img alt="" src="1.jpg"></img>     <img alt="" src="1.jpg">
        //开始匹配content中的<img />标签
        Pattern p_img = Pattern.compile("<(img|IMG)(.*?)(/>|></img>|>)");
        Matcher m_img = p_img.matcher(content);
        boolean result_img = m_img.find();
        if (result_img) {
            while (result_img) {
                //获取到匹配的<img />标签中的内容
                String str_img = m_img.group(2);

                //开始匹配<img />标签中的src
                Pattern p_src = Pattern.compile("(src|SRC)=(\"|\')(.*?)(\"|\')");
                Matcher m_src = p_src.matcher(str_img);
                if (m_src.find()) {
                    str_src = m_src.group(3);
                }
                //结束匹配<img />标签中的src

                //匹配content中是否存在下一个<img />标签，有则继续以上步骤匹配<img />标签中的src
                result_img = m_img.find();
            }
        }
        return str_src;
    }

    /**
     * 关键字高亮显示
     *
     * @param target 需要高亮的关键字
     * @param text   需要显示的文字
     * @return spannable 处理完后的结果，记得不要toString()，否则没有效果
     * SpannableStringBuilder textString = TextUtilTools.highlight(item.getItemName(), KnowledgeActivity.searchKey);
     * vHolder.tv_itemName_search.setText(textString);
     */
    public static SpannableStringBuilder highlight(String text, String target) {
        SpannableStringBuilder spannable = new SpannableStringBuilder(text);
        CharacterStyle span = null;

        Pattern p = Pattern.compile(target);
        Matcher m = p.matcher(text);
        while (m.find()) {
            span = new ForegroundColorSpan(Color.parseColor("#EE5C42"));// 需要重复！
            spannable.setSpan(span, m.start(), m.end(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return spannable;
    }

    /**
     * 从html文本中提取图片地址，或者文本内容
     *
     * @param html       传入html文本
     * @param isGetImage true获取图片，false获取文本
     * @return
     */
    public static ArrayList<String> getTextFromHtml(String html, boolean isGetImage) {
        ArrayList<String> imageList = new ArrayList<>();
        ArrayList<String> textList = new ArrayList<>();
        //根据img标签分割出图片和字符串
        List<String> list = htmlAnalysis(html);
        for (int i = 0; i < list.size(); i++) {
            String text = list.get(i);
            if (text.contains("<img") && text.contains("src=")) {
                //从img标签中获取图片地址
                String imagePath = getImgSrc(text);
                imageList.add(imagePath);
            } else {
                textList.add(text);
            }
        }
        //判断是获取图片还是文本
        if (isGetImage) {
            return imageList;
        } else {
            return textList;
        }
    }

    //doule转字符串，


    public static String format1point(double digit) {

        Log.e("原平均分", digit + "");

        String result = String.format("%.1f", digit);  //可能会丢失精度，四舍五入

        Log.e("损失精度", result + "");

     /*   if (result.indexOf(".") > 0) {
            result = result.replaceAll("0+?$", "");
            result = result.replaceAll("[.]$", "");
        }  //这里会将小数点之后的数据去掉。可以尝试去掉*/

        return result;
    }


    //去除集合中的重复元素

    public static List<String> removeDuplicate(List<String> list)

    {
        Set set = new LinkedHashSet<String>();
        set.addAll(list);
        list.clear();
        list.addAll(set);
        return list;
    }


    public static SpannableStringBuilder highlight(Context context,String text, String keyword){


        SpannableStringBuilder spBuilder = new SpannableStringBuilder(text);
        //匹配规则
        Pattern p0= Pattern.compile(keyword);
        //匹配字段
        Matcher m0 = p0.matcher(spBuilder);
        //上色
        //color = mContext.getResources().getColor(R.color.);
        int color = ContextCompat.getColor(context, R.color.red);
        //开始循环查找里面是否包含关键字 使得一句话中出现多个关键词都会被高亮
        while (m0.find()) {
            int start = m0.start();
            int end = m0.end();
            spBuilder.setSpan(new ForegroundColorSpan(color), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }

        return spBuilder;
    }

}
